package com.guli.order.interceptor;
/*
 * @Author 罗俊
 * @date 2020/11/18 - 12:47 下午
 *
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.guli.common.constant.AuthServerConstant;
import com.guli.common.constant.OrderConstant;
import com.guli.common.pojo.vo.UserInfoVo;
import com.guli.common.to.MemberTo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
public class LoginUserInterceptor implements HandlerInterceptor {

    public static final ThreadLocal<MemberTo> THREAD_LOCAL = new ThreadLocal<>();


//    public static final ThreadLocal<HttpServletRequest> REQUEST_THREAD_LOCAL = new ThreadLocal<>();

    private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        /**
         * 判断，如果是微服务查询订单状态，就直接放行
         * */


        boolean match = ANT_PATH_MATCHER.match("/order/order/info/*", request.getRequestURI());

        if(match){
            log.info("远程微服务调用订单查询接口，直接放行");
            return true;
        }

        boolean matchAliPay = ANT_PATH_MATCHER.match("/mall/payment/alipay/**", request.getRequestURI());
        if(matchAliPay){
            log.info("支付成功的回调地址，放行");
            return true;
        }

        HttpSession session = request.getSession();

        MemberTo attribute = (MemberTo) session.getAttribute(AuthServerConstant.LOGIN_USER_SESSION);

        if (ObjectUtils.isEmpty(attribute)) {
            // 用户session中没有用户信息，跳转登陆
            // Ajax 不支持重定向
            response.sendRedirect(AuthServerConstant.LOGIN_URL + "?redirectUrl=" + OrderConstant.PAY_URL);
            return false;
        }


        if (ObjectUtils.isEmpty(attribute.getId())) {
            // 用户session中没有用户id，（没有登陆）
            response.sendRedirect(AuthServerConstant.LOGIN_URL + "?redirectUrl=" + OrderConstant.PAY_URL);
            return false;
        }

        THREAD_LOCAL.set(attribute);

//        REQUEST_THREAD_LOCAL.set(request);

        return true;
    }
}
